package common

import (
	"encoding/json"
	"fmt"
	"github.com/gogf/gf/os/gtime"
	"strings"
	"time"
)

// json转map
func JsonToMap(jsonStr string) (interface{}, error) {
	//jsonStr := `
	//    {
	//		"name": "张三",
	//		"age": 18
	//    }
	//    `
	var mapResult map[string]interface{}
	err := json.Unmarshal([]byte(jsonStr), &mapResult)
	if err != nil {
		return mapResult, err
	}
	return mapResult, nil
}

// 时间转换工具 将ISO 8601时间转为当地时间戳
func TransformTimestrToTimestamp(timestr string) (int64, error) {
	//2006-01-02 15:04:05 是golang的时间模板，据说是golang语言的诞生时间，2006-01-02 15:04:05类似于我们熟悉的YYYY-MM-dd HH:mm:ss
	result, err := time.ParseInLocation("2006-01-02T15:04:05+0800", timestr, time.Local)
	return result.Unix(), err
}

func IsoToDate() string {
	t := gtime.Now()
	f := "Y-m-dTH:i:s.000Z"
	return strings.Replace(t.Format(f), "CS", "", 1)
}


// 字节的单位转换 保留两位小数
func FormatFileSize(fileSize int64) (size string) {
	if fileSize < 1024 {
		//return strconv.FormatInt(fileSize, 10) + "B"
		return fmt.Sprintf("%.2fB", float64(fileSize)/float64(1))
	} else if fileSize < (1024 * 1024) {
		return fmt.Sprintf("%.2fKB", float64(fileSize)/float64(1024))
	} else if fileSize < (1024 * 1024 * 1024) {
		return fmt.Sprintf("%.2fMB", float64(fileSize)/float64(1024*1024))
	} else if fileSize < (1024 * 1024 * 1024 * 1024) {
		return fmt.Sprintf("%.2fGB", float64(fileSize)/float64(1024*1024*1024))
	} else if fileSize < (1024 * 1024 * 1024 * 1024 * 1024) {
		return fmt.Sprintf("%.2fTB", float64(fileSize)/float64(1024*1024*1024*1024))
	} else { //if fileSize < (1024 * 1024 * 1024 * 1024 * 1024 * 1024)
		return fmt.Sprintf("%.2fEB", float64(fileSize)/float64(1024*1024*1024*1024*1024))
	}
}
